import type { AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios';
import type { AxiosTransform, CreateAxiosOptions } from './types/staxios';

import { Toast } from 'vant';
import STAxios from './STAxios';
import { deepMerge } from '/@/utils';
import { Base64 } from 'js-base64';
import { useUserStoreWithOut } from '/@/store/user';

const transform: AxiosTransform = {
  requestInterceptors(config: AxiosRequestConfig, options: CreateAxiosOptions) {
    if (['development', 'staging'].includes(import.meta.env.MODE)) {
      config.baseURL = 'https://jtest.sdyuntongtianxia.com';
    } else {
      config.baseURL = 'https://t.sdyuntongtianxia.com';
    }

    // config.baseURL = 'https://jtest.sdyuntongtianxia.com';
    return config;
  },
  responseInterceptors(res: AxiosResponse<any>) {
    return res;
  },
  responseInterceptorsCatch(e: AxiosError) {
    const userStore = useUserStoreWithOut();
    if (e.response?.status == 401) {
      userStore.logout(true);
    }
    const message = e.response?.data.msg;
    Toast(message);
    return Promise.reject(e);
  },
  requestCatchHook: (e: Error | AxiosError) => {
    return Promise.reject(e);
  }
};

const createAxios = (opt?: Partial<CreateAxiosOptions>) => {
  return new STAxios(
    deepMerge(
      {
        timeout: 40 * 1000,
        transform,
        headers: {
          'Content-Type': 'application/json;charset=UTF-8'
        }
      },
      opt || {}
    )
  );
};

export default createAxios();
